//
//  AppDelegate+NRWCarAppservice.m
//  New_Runway
//
//  Created by mack on 2018/1/23.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "AppDelegate+NRWCarAppservice.h"
#import "NRWCarGuidePageController.h"
#import "NRWCarLoginController.h"
#import "NRWCarTabbarController.h"
#import "NRWCarNavigationController.h"
#import "NSString+FilePath.h"
#import "JPUSHService.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@implementation AppDelegate (NRWCarAppservice)

-(void)initWindowWithLaunch:(NSDictionary *)launch{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];

    [self loadNewFeatureView:launch];
}


- (void)loadNewFeatureView:(NSDictionary *)launch
{
    NSString *key = (NSString *)kCFBundleVersionKey;

    NSString *lastVersionCode = [NSString stringWithContentsOfFile:[NSString getVersionFilePath] encoding:NSUTF8StringEncoding error:nil];
    NSString *currentVersionCode = [NSBundle mainBundle].infoDictionary[key];
    if ([lastVersionCode isEqualToString:currentVersionCode]) {
        
        [self loadData];
    } else if (launch[UIApplicationLaunchOptionsRemoteNotificationKey]) {
        
        [self loadData];
        [currentVersionCode writeToFile:[NSString getVersionFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    } else {
        
        NRWCarGuidePageController *new = [[NRWCarGuidePageController alloc] init];
        kSelfWeak;
        
        new.completeBlock = ^{
            // 第一次使用软件
            [currentVersionCode writeToFile:[NSString getVersionFilePath] atomically:YES encoding:NSUTF8StringEncoding error:nil];
            
            [weakSelf loadData];
        };
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

        self.window.rootViewController = new;
        [self.window makeKeyAndVisible];
    }
}

-(void)loadData{
    
    
    if ([NRWCarUser sharedUser].didLogin == YES) {
//        NRWCarTabbarController *tabBarVC = [NRWCarTabbarController sharedTabBarVC];
//        NRWCarNavigationController *nav = [[NRWCarNavigationController alloc] initWithRootViewController:tabBarVC];
//        nav.navigationBar.hidden = YES;
//        nav.automaticallyAdjustsScrollViewInsets = NO;
//        [self.window setRootViewController:nav];
//        [self.window makeKeyAndVisible];
        [self signInForData];

        

    }else{
    
    NRWCarLoginController *loginVc = [[NRWCarLoginController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    }
//    NRWCarTabbarController *tabBarVC = [NRWCarTabbarController sharedTabBarVC];
//    NRWCarNavigationController *nav = [[NRWCarNavigationController alloc] initWithRootViewController:tabBarVC];
//    nav.navigationBar.hidden = YES;
//    nav.automaticallyAdjustsScrollViewInsets = NO;
//    self.window.rootViewController = tabBarVC;
//    [self.window makeKeyAndVisible];
//    [self.window setRootViewController:nav];
}

-(void)signInForData{
    if ([NRWCarUser sharedUser].didLogin == YES) {
        NRWCarLoginController *loginVc = [[NRWCarLoginController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
        [AppDelegate shareAppDelegate].window.rootViewController = nav;
        [[AppDelegate shareAppDelegate].window makeKeyAndVisible];
        [SVProgressHUD show];
        NSString *url = [NSString stringWithFormat:@"%@%@",Api,LoginApi];
        NSDictionary *parameter = @{
                                    @"accountName":[NRWCarUser sharedUser].phoneNum ?[NRWCarUser sharedUser].phoneNum : @"" ,
                                    @"accountPassword":[NRWCarUser sharedUser].password ? [NRWCarUser sharedUser].password : @"",
                                    @"applicationId":@"171220110147618",
                                    @"exceptionUrl":@"/controller/LoginJson",
                                    @"loginUrl":@"/controller/LoginJson",
                                    @"logoutUrl":@"/controller/LoginJson"
                                    };
        MJWeakSelf;
        [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:parameter progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
            
        } successBlock:^(id response) {
            if ([response[@"code"] isEqual:@1]) {
                NSDictionary *dataDic = response[@"result"];
                NRWCarUser *model = [NRWCarUser sharedUser];
                model.didLogin = YES;
                model.phoneNum = [NRWCarUser sharedUser].phoneNum;
                model.password = [NRWCarUser sharedUser].password;
                [model setWithDictionary:dataDic];
                [model archive];
                [weakSelf loginSuccess];
                
            }else{
                [weakSelf signOut];
            }
            
            [SVProgressHUD dismiss];

            
            //        [self loginSuccess];
        } failBlock:^(NSError *error) {
            [self signOut];
            [SVProgressHUD dismiss];
        }];
        
        
    }
}
-(void)loginSuccess{
    
    NRWCarTabbarController *tabBarVC = [NRWCarTabbarController sharedTabBarVC];
    NRWCarNavigationController *nav = [[NRWCarNavigationController alloc] initWithRootViewController:tabBarVC];
    nav.navigationBar.hidden = YES;
    nav.automaticallyAdjustsScrollViewInsets = NO;
    [AppDelegate shareAppDelegate].window.rootViewController = nav;
    [[AppDelegate shareAppDelegate].window makeKeyAndVisible];
}
-(void)signOut{
    
    [NRWCarUser reset];
    [[FMDBInfo sharedDataBase] deleteAllCarList];
    NRWCarLoginController *loginVc = [[NRWCarLoginController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVc];
    [AppDelegate shareAppDelegate].window.rootViewController = nav;
    [[AppDelegate shareAppDelegate].window makeKeyAndVisible];
}
+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    
    if ([superVC isKindOfClass:[NRWCarTabbarController class]]) {
        
        UIViewController  *tabSelectVC = ((NRWCarTabbarController*)superVC).selectedViewController;
        
        if ([tabSelectVC isKindOfClass:[NRWCarNavigationController class]]) {
            
            return ((NRWCarNavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[NRWCarNavigationController class]]) {
            
            return ((NRWCarNavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}
-(UIViewController *)getCurrentVC{
    
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
   
    
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}
@end
